<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="计划名称" prop="planName">
        <el-input
          v-model="queryParams.planName"
          placeholder="请输入计划名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="计划状态" prop="planStatus">
        <el-select
          v-model="queryParams.planStatus"
          placeholder="请选择计划状态"
          clearable
          class="!w-240px"
        >
          <el-option label="草稿" :value="0" />
          <el-option label="已提交" :value="1" />
          <el-option label="已审批" :value="2" />
          <el-option label="已发布" :value="3" />
          <el-option label="进行中" :value="4" />
          <el-option label="已完成" :value="5" />
          <el-option label="已取消" :value="6" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openBatchProcess"
          v-hasPermi="['eval:workflow:batch-process']"
        >
          <Icon icon="ep:operation" class="mr-5px" /> 批量处理
        </el-button>
        <el-button
          type="info"
          plain
          @click="openStatistics"
          v-hasPermi="['eval:workflow:statistics']"
        >
          <Icon icon="ep:data-analysis" class="mr-5px" /> 统计分析
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 工作流统计卡片 -->
  <el-row :gutter="20" class="mb-4">
    <el-col :span="4" v-for="(item, index) in statusStatistics" :key="index">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold" :class="item.color">{{ item.count }}</div>
            <div class="text-gray-500">{{ item.label }}</div>
          </div>
          <Icon :icon="item.icon" :class="`text-4xl ${item.color}`" />
        </div>
      </el-card>
    </el-col>
  </el-row>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="计划编码" align="center" prop="planCode" width="120" />
      <el-table-column label="计划名称" align="center" prop="planName" width="200" />
      <el-table-column label="职业名称" align="center" prop="professionName" width="150" />
      <el-table-column label="当前状态" align="center" prop="planStatus" width="100">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.planStatus)">
            {{ getStatusText(scope.row.planStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="可执行操作" align="center" width="200">
        <template #default="scope">
          <div class="flex flex-wrap gap-1">
            <el-button
              v-for="action in scope.row.availableActions"
              :key="action.targetStatus"
              :type="action.actionType"
              size="small"
              @click="handleAction(scope.row, action)"
            >
              {{ action.actionName }}
            </el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="报名时间" align="center" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.registrationStartDate) }} ~ {{ formatDate(scope.row.registrationEndDate) }}
        </template>
      </el-table-column>
      <el-table-column label="评价时间" align="center" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.evaluationStartDate) }} ~ {{ formatDate(scope.row.evaluationEndDate) }}
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openWorkflowDetail(scope.row.id)"
            v-hasPermi="['eval:workflow:query']"
          >
            流转详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="openConditionCheck(scope.row.id)"
            v-hasPermi="['eval:workflow:check']"
          >
            条件检查
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 工作流详情弹窗 -->
  <WorkflowDetail ref="workflowDetailRef" />
  
  <!-- 条件检查弹窗 -->
  <ConditionCheck ref="conditionCheckRef" />
  
  <!-- 批量处理弹窗 -->
  <BatchProcess ref="batchProcessRef" @success="getList" />
  
  <!-- 统计分析弹窗 -->
  <WorkflowStatistics ref="statisticsRef" />
  
  <!-- 操作确认弹窗 -->
  <ActionConfirm ref="actionConfirmRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter, formatDate } from '@/utils/formatTime'
import { EvalPlanVO, getPlanPage } from '@/api/eval/plan'
import { 
  EvalWorkflowActionVO,
  getAvailableActions,
  getWorkflowStatistics
} from '@/api/eval/workflow'
import WorkflowDetail from './WorkflowDetail.vue'
import ConditionCheck from './ConditionCheck.vue'
import BatchProcess from './BatchProcess.vue'
import WorkflowStatistics from './WorkflowStatistics.vue'
import ActionConfirm from './ActionConfirm.vue'

/** 工作流管理 */
defineOptions({ name: 'EvalWorkflow' })

const message = useMessage() // 消息弹窗

const loading = ref(true) // 列表的加载中
const list = ref<any[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const statusStatistics = ref<any[]>([]) // 状态统计
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  planName: undefined,
  planStatus: undefined
})
const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getPlanPage(queryParams)
    
    // 为每个计划加载可执行操作
    const listWithActions = await Promise.all(
      data.list.map(async (plan: EvalPlanVO) => {
        const availableActions = await getAvailableActions(plan.id!)
        return {
          ...plan,
          availableActions
        }
      })
    )
    
    list.value = listWithActions
    total.value = data.total
    
    // 加载统计数据
    await loadStatistics()
  } finally {
    loading.value = false
  }
}

/** 加载统计数据 */
const loadStatistics = async () => {
  try {
    const statistics = await getWorkflowStatistics()
    statusStatistics.value = [
      {
        label: '草稿',
        count: statistics.draftCount || 0,
        color: 'text-gray-600',
        icon: 'ep:document'
      },
      {
        label: '已提交',
        count: statistics.submittedCount || 0,
        color: 'text-yellow-600',
        icon: 'ep:upload'
      },
      {
        label: '已审批',
        count: statistics.approvedCount || 0,
        color: 'text-green-600',
        icon: 'ep:check'
      },
      {
        label: '已发布',
        count: statistics.publishedCount || 0,
        color: 'text-blue-600',
        icon: 'ep:promotion'
      },
      {
        label: '进行中',
        count: statistics.inProgressCount || 0,
        color: 'text-orange-600',
        icon: 'ep:loading'
      },
      {
        label: '已完成',
        count: statistics.completedCount || 0,
        color: 'text-purple-600',
        icon: 'ep:success-filled'
      }
    ]
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 工作流详情操作 */
const workflowDetailRef = ref()
const openWorkflowDetail = (planId: number) => {
  workflowDetailRef.value.open(planId)
}

/** 条件检查操作 */
const conditionCheckRef = ref()
const openConditionCheck = (planId: number) => {
  conditionCheckRef.value.open(planId)
}

/** 批量处理操作 */
const batchProcessRef = ref()
const openBatchProcess = () => {
  batchProcessRef.value.open()
}

/** 统计分析操作 */
const statisticsRef = ref()
const openStatistics = () => {
  statisticsRef.value.open()
}

/** 操作确认操作 */
const actionConfirmRef = ref()
const handleAction = (plan: EvalPlanVO, action: EvalWorkflowActionVO) => {
  actionConfirmRef.value.open(plan, action)
}

/** 获取状态标签类型 */
const getStatusTagType = (status: number) => {
  const typeMap = {
    0: '',
    1: 'warning',
    2: 'success',
    3: 'primary',
    4: 'warning',
    5: 'success',
    6: 'danger'
  }
  return typeMap[status] || ''
}

/** 获取状态文本 */
const getStatusText = (status: number) => {
  const textMap = {
    0: '草稿',
    1: '已提交',
    2: '已审批',
    3: '已发布',
    4: '进行中',
    5: '已完成',
    6: '已取消'
  }
  return textMap[status] || '未知'
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
